package com.hust360.percent.activity;

import java.util.ArrayList;
import java.util.Iterator;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.R;
import com.hust360.percent.pojo.City;
import com.hust360.percent.pojo.Province;
import com.hust360.percent.utils.ActivityUtils;

public class CityActivity extends Activity {

	public static final String TAG = "CityActivity";

	PercentApplication application;

	/**
	 * 显示城市的列表视图
	 */
	ListView listView;

	/**
	 * 搜索城市的输入框
	 */
	AutoCompleteTextView editText;

	/**
	 * 搜索按钮
	 */
	ImageView searchBtn;

	/**
	 * 标题，用来显示的当前地点
	 */
	TextView title;

	/**
	 * 城市的数据库
	 */
	SQLiteDatabase db;

	/**
	 * 省份的Cursor
	 */
	Cursor prvcCursor;

	/**
	 * 城市的Cursor
	 */
	Cursor ctCursor;

	/**
	 * 
	 */
	ArrayList<Province> prvcList;

	/**
	 * 
	 */
	ArrayList<City> ctList;

	/**
	 * 
	 */
	CityAdapter adapter;

	/**
	 * 异步查询数据的句柄
	 */
	Handler handler;

	/**
	 * 异步查询的线程对象
	 */
	HandlerThread thread;

	/**
	 * 查询到匹配的条目时存放的集合
	 */
	ArrayList<Object> matchList;

	ArrayList<City> subCity;

	/**
	 * 当获得匹配的条目时发给handler的消息的标志
	 */
	private static final int GET_MATCH_OBJECT = 0;

	/**
	 * 返回按钮
	 */
	private ImageButton backBtn;

	/**
	 * 输入法对象
	 */
	InputMethodManager manager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_city);
		ActivityUtils.addActivity(this);
		application = (PercentApplication) getApplication();
		db = application.getCityDB();

		prvcList = new ArrayList<Province>(85);
		ctList = new ArrayList<City>(100);
		subCity = new ArrayList<City>(50);

		synchronized (db) {
			prvcCursor = db.query("province", null, null, null, null, null,
					"name");
			ctCursor = db.query("city", null, null, null, null, null, null);
		}

		Province province;
		while (prvcCursor.moveToNext()) {
			province = new Province();
			province.id = prvcCursor.getLong(0);
			province.name = prvcCursor.getString(1);
			prvcList.add(province);
		}

		City city;
		while (ctCursor.moveToNext()) {
			city = new City();
			city.id = ctCursor.getLong(0);
			city.name = ctCursor.getString(1);
			city.province = ctCursor.getLong(2);
			ctList.add(city);
		}

		matchList = new ArrayList<Object>(5);
		// 根据id获取所有的view
		findAllViewById();
		// 初始化线程
		initThread();

		title.setText("当前-" + application.getCurCity().name);
		manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
	}

	private void findAllViewById() {
		listView = (ListView) findViewById(R.activity_city.listview);
		adapter = new CityAdapter();
		listView.setAdapter(adapter);
		ItemClick itemClick = new ItemClick();
		listView.setOnItemClickListener(itemClick);
		editText = (AutoCompleteTextView) findViewById(R.activity_city.eidt);
		editText.addTextChangedListener(new CityEditChange());
		editText.setOnFocusChangeListener(new EditFocusChange());
		searchBtn = (ImageView) findViewById(R.activity_city.search);
		title = (TextView) findViewById(R.activity_city.curCity);
		backBtn = (ImageButton) findViewById(R.activity_city.back);
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (adapter.showprvc == false) {
					adapter.showprvc = true;
					adapter.notifyDataSetChanged();
				} else {
					finish();
				}
			}
		});
	}

	/**
	 * 初始化线程对象
	 */
	@SuppressLint("HandlerLeak")
	private void initThread() {
		thread = new HandlerThread("city activity cursor thread");
		thread.start();
		handler = new Handler(thread.getLooper()) {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.arg1) {
				case GET_MATCH_OBJECT:
					CityActivity.this.runOnUiThread(new Runnable() {

						@Override
						public void run() {
							adapter.notifyDataSetChanged();
						}
					});
					break;

				default:
					break;
				}
			}
		};
	}

	@Override
	protected void onDestroy() {
		prvcCursor.close();
		ctCursor.close();
		thread.interrupt();
		super.onDestroy();
		ActivityUtils.removeActivity(this);
	}

	private class CityAdapter extends BaseAdapter {

		boolean hasMatch = false;

		// 默认显示的是省份，用户点击之后显示对应省份的城市
		boolean showprvc = true;

		@Override
		public int getCount() {
			if (hasMatch) {
				int count = matchList.size() + 1;
				count += showprvc ? 1 + prvcList.size() : subCity == null ? 0
						: subCity.size() + 1;
				return count;
			} else {
				return showprvc ? prvcList.size() : subCity == null ? 0
						: subCity.size();
			}
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			TextView textView = (TextView) arg1;
			if (textView == null) {
				textView = (TextView) CityActivity.this.getLayoutInflater()
						.inflate(R.layout.city_item, null);
			}

			if (hasMatch) {
				int pt = textView.getPaddingTop();
				int pr = textView.getPaddingRight();
				int pb = textView.getPaddingBottom();
				if (arg0 == 0) {
					textView.setText("你要找的是?");
					textView.setPadding(10, pt, pr, pb);
				} else if (arg0 == matchList.size() + 1) {
					String text = showprvc ? "省份" : "城市";
					textView.setText(text);
					textView.setPadding(10, pt, pr, pb);
				} else if (arg0 > 0 && arg0 < matchList.size() + 1) {
					Object object = matchList.get(arg0 - 1);
					if (object instanceof Province) {
						Province province = (Province) object;
						textView.setText(province.name);
						textView.setPadding(20, pt, pr, pb);
					} else if (object instanceof City) {
						City city = (City) object;
						textView.setText(city.name);
						textView.setPadding(20, pt, pr, pb);
					}
				} else if (arg0 > matchList.size() + 1) {
					if (showprvc) {
						textView.setText(prvcList.get(arg0 - matchList.size()
								- 2).name);
					} else {
						textView.setText(subCity.get(arg0 - matchList.size()
								- 2).name);
					}
				}
			} else if (showprvc) {
				textView.setText(prvcList.get(arg0).name);
			} else {
				textView.setText(subCity.get(arg0).name);
			}
			return textView;
		}
	}

	private class CityEditChange implements TextWatcher {
		@Override
		public void afterTextChanged(Editable s) {
			handler.post(new Runnable() {
				@Override
				public void run() {

					Log.i(TAG, "after text change!");

					matchList.clear();
					String string = editText.getText().toString();

					if (!"".equals(string)) {
						Iterator<City> iterator = ctList.iterator();
						City city;
						while (iterator.hasNext()) {
							city = iterator.next();
							if (city.name.indexOf(string) != -1) {
								matchList.add(city);
							}
						}

						Province province;
						Iterator<Province> iterator2 = prvcList.iterator();
						while (iterator2.hasNext()) {
							province = iterator2.next();
							if (province.name.indexOf(string) != -1) {
								matchList.add(province);
							}
						}
					} else {
						adapter.hasMatch = false;
						Message message = handler.obtainMessage();
						message.arg1 = GET_MATCH_OBJECT;
						handler.sendMessage(message);
					}

					if (matchList.size() != 0) {
						adapter.hasMatch = true;

					} else {
						adapter.hasMatch = false;
					}
					Message message = handler.obtainMessage();
					message.arg1 = GET_MATCH_OBJECT;
					handler.sendMessage(message);
				}
			});
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}
	}

	private class ItemClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			if (adapter.hasMatch) {
				if (0 < arg2 && arg2 < matchList.size() + 1) {
					Object object = matchList.get(arg2 - 1);
					if (object instanceof City) {
						City city = (City) object;
						Log.i(TAG, city.toString());
						application.setCurCity(city);
						setResult(RESULT_OK);
						finish();
					} else if (object instanceof Province) {

						subCity.clear();
						Province province = (Province) object;
						Log.i(TAG, province.toString());

						City city;
						Iterator<City> iterator = ctList.iterator();
						while (iterator.hasNext()) {
							city = iterator.next();
							if (city.province == province.id) {
								subCity.add(city);
							}
						}
						adapter.showprvc = false;
						adapter.notifyDataSetChanged();
					}
				} else if (arg2 >= matchList.size() + 2 && adapter.showprvc) {
					Province province = prvcList.get(arg2 - matchList.size()
							- 2);
					Log.i(TAG, province.toString());

					subCity.clear();
					City city;
					Iterator<City> iterator = ctList.iterator();
					while (iterator.hasNext()) {
						city = iterator.next();
						if (city.province == province.id) {
							subCity.add(city);
						}
					}
					adapter.showprvc = false;
					adapter.notifyDataSetChanged();

				} else if (arg2 > matchList.size() + 2 && !adapter.showprvc) {
					City city = subCity.get(arg2 - matchList.size() - 2);
					Log.i(TAG, city.toString());
					application.setCurCity(city);
					setResult(RESULT_OK);
					finish();
				}
			} else {
				if (adapter.showprvc) {
					Province province = prvcList.get(arg2);
					Log.i(TAG, province.toString());

					subCity.clear();
					City city;
					Iterator<City> iterator = ctList.iterator();
					while (iterator.hasNext()) {
						city = iterator.next();
						if (city.province == province.id) {
							subCity.add(city);
						}
					}
					adapter.showprvc = false;
					adapter.notifyDataSetChanged();

				} else {
					City city = subCity.get(arg2);
					application.setCurCity(city);
					setResult(RESULT_OK);
					finish();
					Log.i(TAG, city.toString());
				}
			}
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (manager.isActive(editText) && editText.isFocused()) {
				manager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
				editText.clearFocus();
				editText.setText(""); //在输入框失去焦点的时候，清空输入框里面的文字
				return true;
			} else if (!adapter.showprvc) {
				adapter.showprvc = true;
				adapter.notifyDataSetChanged();
				return true;
			}
		}
		editText.clearFocus();
		return super.onKeyDown(keyCode, event);
	}

	private class EditFocusChange implements OnFocusChangeListener {

		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			if (hasFocus) {
				listView.scrollTo(0, 0);
			}
		}

	}

}
